import {
  ONE_LEVEL_ROUTE_CHANGE,
  TWO_LEVEL_ROUTE_CHANGE,
  TOGGLE_SHOW_LOGINBOX,
  SET_COOKIEACT,
  SET_LOGINSTATUSACT,
  SET_PROFILEACT,
  SET_CURRENTSONGSLIST_FUN,
  SET_CURRENTSONG_FUN,
  SET_CURRENT_DETAIL,
  SET_CURRENT_SONG_NEWACT,
  ERR_MESSAGE,
  SEND_LRC,
  SET_CURRENTTIME,
  SET_CURRENTSONG_STATUS,
  SET_LRCARR,
  REVICE_SONGLIST,
  REVICE_MP3List,
  SET_CURRENTSONG_MP3,
  REVICE_CURRENTSONG_DETAIL,
  REVICE_CURRENT_MP3,
  TOGGLE_PLAYSTATUSEND,
  ADD_MP3LIST,
  ADD_SONGLIST,
  ADD_BROTHERNODECHANGETIME
} from "./constants";
import { songMp3ListReq, songsListReq, songDetailwithIdsReq, getLrcWithIdReq } from '@/utils/api/user'

export const onelevelRouteChange = (id) => ({
  type: ONE_LEVEL_ROUTE_CHANGE,
  id,
})

export const twolevelRouteChange = (id) => ({
  type: TWO_LEVEL_ROUTE_CHANGE,
  id,
})

export const toggleShowLoginBox = () => ({
  type: TOGGLE_SHOW_LOGINBOX,
})

export const setCookieAct = (data) => ({
  type: SET_COOKIEACT,
  payload: data,
})

export const setLoginStatusAct = (data) => ({
  type: SET_LOGINSTATUSACT,
  payload: data,
})

export const setProfileAct = (data) => ({
  type: SET_PROFILEACT,
  payload: data,
})

export const setCurrentsongslist = (data) => ({
  type: SET_CURRENTSONGSLIST_FUN,
  payload: data,
})

// export const setListAction = (data) => {
//   return async (dispatch) => {
//     const res = await songsMylike()
//     if (res.data.code === 200) {
//       let dailySongs = res.data.songs
//       dispatch(setCurrentsongslist(dailySongs))
//       // setCurrentDetailAct.name
//       let songOne = dailySongs[0]
//       dispatch(setCurrentDetailAct(songOne))
//       const res2 = await songMp3ListReq({id: songOne.id})
//       if (res2.data.code === 200) {
//         let songs = res2.data.data
//         dispatch(setCurrentsong(songs[0]))
//         dispatch(getLrcWithIdAct(songOne.id))
//       }else{
//         dispatch(err_message(res2.data.msg))
//       }
//       // currentSong.url
//       // dispatch(setCurrentsong())

//     }else{
//       dispatch(err_message(res.data.msg))
//     }
//   }
  

// };

export const setCurrentsong = (data) => ({
  type: SET_CURRENTSONG_FUN,
  payload: data,
})

export const setCurrentDetailAct = (data) => ({
  type: SET_CURRENT_DETAIL,
  payload: data,
})

export const err_message = (data) => ({
  type: ERR_MESSAGE,
  payload: data,
})

export const sendLrc = (data) => ({
  type: SEND_LRC,
  payload: data,
})

export const setCurrentSongStatus = (data) => ({
  type: SET_CURRENTSONG_STATUS,
  payload: data
})

export const getLrcWithIdAct = (data) => {
  return async (dispatch) => {
    const res = await getLrcWithIdReq({id: data.id})
    // console.log(res.data, 'lsry');
    if (res.data.code === 200) {

      // let lyric = res.data.lrc.lyric;
      // let lrcTimes = [];
      // let lrcNames = [];
      // lyric.split("\n").forEach((item) => {
      //   let reg = new RegExp(/\[(\S*)\]/);

      //   let strName = String(item.replace(reg, ""));
      //   lrcNames.push(strName);

      //   let matchResultArr = item.match(reg);
      //   let str = matchResultArr ? matchResultArr[1] : "";

      //   lrcTimes.push(str);
      // });

      // console.log(lrcNames, "lrcNames");
      // console.log(lrcTimes, "lrcTimes");
      // res.data.lrcNames = lrcNames
      // res.data.lrcTimes = lrcTimes

      try {
        dispatch(sendLrc(res.data.lrc))
        handleDataLrc(dispatch, res.data.lrc.lyric)
      } catch (error) {
        alert('请求失败!')
        console.log(error, 'error');
      }
    }
  }
}
export const handleDataLrc = (dispatch, lyric) => {
  let lrcTimesArr = [];
  let lrcNamesArr = [];
  if (!lyric) {
    return
  }
  lyric.split("\n").forEach((item) => {
    let reg = new RegExp(/\[(\S*)\]/);

    let strName = String(item.replace(reg, ""));
    // if (strName) {
      lrcNamesArr.push(strName);
    // }

    let matchResultArr = item.match(reg);
    let str = matchResultArr ? matchResultArr[1] : "";
    let strNameRes = ''
    if (strName) {
      let strNameResArr = str.replace('.', ":").split(':')
      let min = parseInt(strNameResArr[0])
      let second = parseInt(strNameResArr[1])
      let msecond = parseInt(strNameResArr[2])
      strNameRes = msecond + second * 1000 + min * 1000 * 60
    }
    // if (strNameRes) {
      lrcTimesArr.push(strNameRes);
    // }

    // lrcTotalArr.push({lrcNames: strName, lrcTimes: strNameRes})
  })
  
  // console.log(lrcTotalArr, 'lrcTotalArr LrcContainer action');

  if (dispatch) {
    dispatch(setLrcArr({key: 'lrcNamesArr', value: lrcNamesArr}));
    dispatch(setLrcArr({key: 'lrcTimesArr', value: lrcTimesArr}));
  }

  return {lrcNamesArr, lrcTimesArr}
  // dispatch(setLrcArr({key: 'lrcTotalArr', value: lrcTotalArr}));
}

export const setLrcArr = (data) => ({
  type: SET_LRCARR,
  payload: data
})

export const setCurrentSongNewAct = (data) => {
  // console.log('setCurrentSongNewAct in action' + data);
  return async (dispatch) => {
    const res = await songMp3ListReq({id: data.id})
    // console.log('res.data in getSongwith down' + res.data);
    if (res.data.code === 200) {
      let songs = res.data.data
      if (songs[0].url) {
        // console.log(songs[0].url, 'onready');
        dispatch(setCurrentSongStatus(true))
      }else{
        dispatch(setCurrentSongStatus(false))
      }
      dispatch(setCurrentsong(songs[0]))
      dispatch(setCurrentDetailAct(data))
      
    }else{
      dispatch(err_message(res.data.msg))
    }
  }
};

export const setCurrentTime = (data) => ({
  type: SET_CURRENTTIME,
  payload: data,
})


/*
- receiveSongList (在playtoplist组件中接收ids)
  1. 接受ids (array)
  2. 通过ids获取对应的详情列表
  3. 通过ids获取对应的歌曲列表
  4. 通过第一个id设置歌曲的详情（这里直接传入第一个id触发一个setCurrentSong的action）
  5. 设置一个状态songList
  6. songList : [
    {name: 'xxx', author: 'xxx', time: '8:09', id: '1230', url: 'mp4.xxx.'},
    {name: 'xxx', author: 'xxx', time: '8:09', id: '1231', url: 'mp4.xxx.'},
    {name: 'xxx', author: 'xxx', time: '8:09', id: '1232', url: 'mp4.xxx.'},
  ]
*/
export const receiveSongList = (ids) => {
  return async dispatch => {
    let idstr = ids.join(',')
    const res = await songDetailwithIdsReq({ids: idstr})
    if (res.data.code === 200) {
      let data = res.data.songs
      dispatch({type: REVICE_SONGLIST, payload: data})
    }
    const resTwo = await songMp3ListReq({id: idstr})
    if (resTwo.data.code === 200) {
      let data = resTwo.data.data
      dispatch({type: REVICE_MP3List, payload: data})
    }
    dispatch(setCurrentSongDetail(ids[0]))
  }
}

export const setCurrentSongDetail = (id) => {
  return async dispatch => {
    const resOne = await songDetailwithIdsReq({ids: id})
    if (resOne.data.code === 200) {
      let data = resOne.data.songs[0]
      dispatch({type: REVICE_CURRENTSONG_DETAIL, payload: data})
    }
    const resTwo = await songMp3ListReq({id})
    if (resTwo.data.code === 200) {
      let data = resTwo.data.data[0]
      dispatch({type: REVICE_CURRENT_MP3, payload: data})
    }
    const resThree = await getLrcWithIdReq({id})
    if (resThree.data.code === 200) {
      if (resThree.data.lrc) {
        dispatch(sendLrc(resThree.data.lrc))
        handleDataLrc(dispatch, resThree.data.lrc.lyric)
      }else{
        let lrc = {lyric: '[00:00.000] 暂无歌词'}
        debugger
        dispatch(sendLrc(lrc))
        handleDataLrc(dispatch, lrc.lyric)
      }
    }
  }
}

/*
- receiveCurrentSongDetail (id)
  作用： 设置当前的播放歌曲。并且获取对应的歌词（两个请求）
  1. 只接收接受一个id。
  2. 根据对应id，获取第一首歌的mp3 URl
  3. 获取当前歌曲的歌词
  4. 触发另一个获取歌词数组的action
  5. lrc需要的歌词数据：names 和 times
  */


// 设置播放结束状态
export const togglePlayStatusEnd = (data) => ({
  type: TOGGLE_PLAYSTATUSEND,
  payload: data
})

// 添加歌曲到歌单
// export const togglePlayStatusEnd = (data) => {
//   let id = data.id
  
//   return async dispatch => {

//   }
// }

// 设置歌曲列表

/**
 * 单曲播放 ids.length == 1
 *  - 直接加入歌单播放
 * 专辑播放 ids.length > 1
 *  - 加入专辑所有歌曲
 * 
 * type == 1 ? 表示上方的播放按钮
 * 1. 加入歌单
 * 2. 播放第一首歌
 * 
 * type == 2 ? 表示专辑列表的播放按钮
 * 1. 加入歌单
 * 2. 播放这首歌
 */
// 点击添加歌单的action
export const addSongListAction = (data) => {
  console.log(data, 'data');
  return async dispatch => {
    const res = await songDetailwithIdsReq({ids: data.ids})
    console.log(res, ' rdata');
    if (res.data.code === 200) {
      let data = res.data.songs
      dispatch({type: ADD_SONGLIST, payload: data})
    }
  }
}

export const addBrothernodechangetime = () => ({
  type: ADD_BROTHERNODECHANGETIME,
})


// 添加歌单并且播放歌曲
export const playSongAction = (id, type = 2, songArr = []) => {
  return dispatch => {
    // 直接接收一个ids : String 加入歌单 播放最后一首
    if (type == 1) {
      // 播放全部
      let idarr = []
      songArr.forEach(item => {
        idarr.push(item.id)
      });
      let ids = idarr.join(',')
      console.log(ids, 'ids')

      dispatch(addSongListAction({ids}));
      let id = ''
      if (ids && ids.length) {
        let idarr = ids.split(',')
        id = idarr[idarr.length - 1]
      }else{
        id = ids
      }
      console.log(id, 'id')
      dispatch(setCurrentSongDetail(id));
      dispatch(addBrothernodechangetime())
    }else{
      dispatch(addSongListAction({ids: id}));
      dispatch(setCurrentSongDetail(id));
      dispatch(addBrothernodechangetime())
    }

  }
}

// 添加歌单
export const addSongAction = (ids, type = 2, songArr = []) => {
  return dispatch => {
    // 如果type == 2 songArr 是必须的参数
    // 如果type == 1 直接姜ids 添加歌单
    if (type == 1) {
      // 接收ids: String 直接加入歌单
      let idarr = []
      songArr.forEach(item => {
        idarr.push(item.id)
      });
      let idstr = idarr.join(',')
  
      dispatch(addSongListAction({ids: idstr}));
    }else{
      dispatch(addSongListAction({ids: ids}));
    }

  }
  
}